import { useLoginStore } from '@/stores/login'
declare const uni: any

const genOption = (reqOptions) => {
  const { token } = useLoginStore()

  const { method, data } = reqOptions
  let fetchMethod = method
  //  ['options', 'get', 'GET', 'HEAD', 'PATCH', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'head', 'patch', 'post', 'put', 'delete', 'connect', 'trace']
  const methodTypes = ['get', 'GET', 'PATCH', 'POST', 'PUT', 'DELETE', 'patch', 'post', 'put', 'delete']
  if (!method || !methodTypes.includes(method)) {
    fetchMethod = 'get'
  }
  const fetchOptions: any = {
    method: fetchMethod,
    ...reqOptions,
  }
  if (isNotNilOrEmpty(data)) {
    fetchOptions.data = data
  }
  fetchOptions.header = reqOptions?.headers || {}
  if (isNotNilOrEmpty(token)) {
    fetchOptions.header.accesstoken = token
  }
  return fetchOptions
}

// 标准请求工具，分离 url，数据和请求设置。仅限客户端使用
export const Fetch = async (url: string, reqOptions: any = {}): Promise<{
  status: number
  data: any
  error: any
}> => {
  let data, error, status
  const reqUrl = /^https?:/.test(url) ? url : `${baseUrl}${url}`

  // 显示加载动画，除非明确设置不显示


  try {
    await request({
      url: reqUrl,
      ...genOption(reqOptions),
      complete: (res: any) => {
        status = res.statusCode
        error = res.errMsg
        data = res.data
      },
    })

    if (data.code !== 0) {
      if (data.code === 401) {
        // uni.showToast({
        //   title: '正在前往登录',
        //   icon: 'error',
        //   duration: 1600,
        // })
        setTimeout(() => {
          // uni.reLaunch({ url: '/pages/index' })
        }, 1600)
        return { status, data, error }
      }
      if (data.code === 403) {
        // 显示登录过期对话框
        // uni.showModal({
        //   title: '提示',
        //   content: '登录已过期，将返回登录页重新登录',
        //   showCancel: false,
        //   success: function (res) {
        //     if (res.confirm) {
        //       // 清除登录信息
        //       uni.removeStorageSync('token');
        //       uni.removeStorageSync('userInfo');

        //       // 返回登录页
        //       uni.reLaunch({
        //         url: '/pages/login'
        //       });
        //     }
        //   }
        // });
      } else if (data.code === 10001) {
        setTimeout(() => {
          uni.reLaunch({
            url: `/pages/ClosingTime?title=${data.msg}`,
          })
        }, 1000)
      }
      // if (data.code === 500 || data.code === 75301 || data.code === -1 || data.code === 400) return { status, data, error }
      // uni.showToast({
      //   title: data.msg,
      //   icon: 'none',
      //   duration: 1600,
      // })
    }
    return { status, data, error }
  } finally {
    // 无论请求成功还是失败都关闭加载动画
    if (reqOptions.showLoading !== false) {
    }
  }
}
